<?php
declare (strict_types=1);

namespace app\admin\logic\site;

use app\admin\logic\market\ticket\Ticket;
use app\admin\logic\system\Log;
use app\admin\model\site\Template as TemplateModel;
use app\common\exception\LogicException;
use think\db\exception\DbException;
use think\Model;
use think\Paginator;

/**
 * Class Template
 *
 * @package app\admin\logic\site
 */
class Template extends TemplateModel
{

    /**
     * getList
     *
     * @param array       $map
     * @param string|null $templateType
     * @return Paginator
     * @throws DbException
     */
    public function getList(array $map = [], ?string $templateType = null)
    {
        if ($templateType) {
            $list = $this->where('template_type', $templateType)
                ->where($map)
                ->order('create_time', 'DESC')
                ->append(['template_type_text'])
                ->paginate($this->getListRows());
        } else {
            $list = $this->where($map)->order('create_time', 'DESC')->paginate($this->getListRows());
        }

        // 是否没有配置模板: 取默认模板
        if ($list->isEmpty()) {
            $map[] = ['is_system', '=', 1];
            $map[] = ['template_type', '=', $templateType];
            $map[] = ['mhm_id', '=', 0];
            $list  = $this->withoutGlobalScope(['mhm'])
                ->where($map)
                ->order('create_time', 'DESC')
                ->append(['template_type_text'])
                ->paginate($this->getListRows());
            // 设置第一条数据使用状态
            $list->first(function ($first) {
                $first->is_used = 1;
            });

        }

        return $list;
    }

    /**
     * created
     *
     * @param array  $data
     * @param string $templateType
     * @return bool
     */
    public function created(array $data, string $templateType)
    {
        $data['template_type'] = $templateType;
        // 验证数据
        $this->getValidate()->scene('create')->failException()->check($data);

        $saved = [
            'mhm_id'        => request()->mhm_id,
            'title'         => $data['title'],
            'template_type' => $templateType,
            'template_data' => [],
        ];

        // 创建成功
        if (!$this->create($saved)) {
            throw new LogicException('创建失败');
        }

        Log::write('新建模板【' . $saved['title'] . '】', 'template', 'create', true);

        return true;
    }

    /**
     * getInfoById
     *
     * @param int $id
     * @return Template|array|Model
     */
    public function getInfoById(int $id)
    {
        return $this->withoutGlobalScope(['mhm'])->where('id', $id)->findOrEmpty();
    }

    /**
     * updated
     *
     * @param       $id
     * @param array $data
     * @return Template|array|Model
     */
    public function updated($id, array $data)
    {
        $template = $this->where('id', $id)->findOrFail();
        if (isset($data['title'])) {
            $template->title = $data['title'];
        }

        if (!$template->save()) {
            throw new LogicException('修改失败');
        }

        Log::write('编辑模板【' . $template->title . '】', 'template', 'update', true);

        return $template;
    }

    /**
     * updated
     *
     * @param $id
     * @param $field
     * @param $value
     * @return Ticket|array|Model
     */
    public function updatedBy($id, $field, $value)
    {
        $template = $this->withoutGlobalScope(['mhm'])->where('id', $id)->findOrFail();
        // 非平台编辑模板  且当前模板是默认模板
        if (!request()->is_platform && $template->is_system == 1) {
            // 机构是否有模板
            $mhmTemplate = $this->where('from_id', $id)->findOrEmpty();
            if ($mhmTemplate->isEmpty()) {
                // 给机构添加默认模板
                $saved = [
                    'mhm_id'        => request()->mhm_id,
                    'title'         => $template->title,
                    'template_type' => $template->template_type,
                    'template_data' => $template->template_data,
                    'is_used'       => 1,
                    'is_system'     => 0,
                    'from_id'       => $id
                ];

                $template = $this->create($saved);
            } else {
                $template = $mhmTemplate;
            }
            // 重置当前修改的对象
            $id = $template->getAttr('id');

        }
        if ($template->getAttr('mhm_id') != request()->mhm_id) {
            throw new LogicException('操作失败', '模板不属于当前机构，无权限操作');
        }

        // 启用模板
        if ($field === 'is_used') {
            // 移除其他模板状态
            TemplateModel::update(['is_used' => 0], [
                'template_type' => $template->template_type,
                'is_used'       => 1
            ]);
        }

        $ret = TemplateModel::update([$field => $value], ['id' => $id]);

        if (!$ret) {
            throw new LogicException('修改失败');
        }

        if ($field === 'is_used') {
            $txt = $value == 1 ? '启用' : '禁用';
            Log::write($txt . '模板【' . $template->title . '】', 'template', 'update', true);
        } else {
            Log::write('编辑模板【' . $template->title . '】', 'template', 'update', true);
        }

        return $template;
    }

    /**
     * deleted
     *
     * @param $id
     */
    public function deleted($id)
    {
        $template = $this->where('id', $id)->findOrFail();

        $title = $template->getAttr('title');

        if (!$template->delete()) {
            throw new LogicException("删除失败");
        }

        Log::write('删除模板【' . $title . '】', 'template', 'delete', true);
    }

}
